<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;

/**
 * 权限
 * @property int $id
 * @property string $name
 * @property string $title
 * @property int $type
 * @property int $parent_id
 * @property int $sort
 * @property Carbon $created_at
 * @property Carbon $updated_at
 * @property Collection $roles 拥有此权限的角色
 */
class Permission extends Model
{
    // 权限类型
    const TYPE_MENU = 1; // 菜单
    const TYPE_BUTTON = 2; // 按钮
    protected $guarded = [];

    /**
     * 父权限
     */
    public function parent(): BelongsTo
    {
        return $this->belongsTo(Permission::class, 'parent_id');
    }

    /**
     * 子权限
     */
    public function children(): HasMany
    {
        return $this->hasMany(Permission::class, 'parent_id')->orderBy('sort', 'asc');
    }

    /**
     * 拥有此权限的角色
     */
    public function roles(): BelongsToMany
    {
        return $this->belongsToMany(Role::class, 'role_has_permissions', 'permission_id', 'role_id')
           ;
    }

    /**
     * 检查是否是顶级菜单
     */
    public function isTopLevelMenu(): bool
    {
        return $this->parent_id == null && $this->type == self::TYPE_MENU;
    }

    /**
     * 获取所有子权限（递归）
     */
    public function allChildren(): Builder|HasMany
    {
        return $this->children()->with('allChildren');
    }
}
